import Vue from 'vue'
import Vuex from 'vuex'
import { logout } from '@/api/auth'
import { getUserInfo,getTeacherUserInfo } from '@/api/user'
import { passwordLogin, smsLogin, weixinMiniAppLogin,login } from '@/api/auth'

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'

Vue.use(Vuex) // vue的插件机制

// Vuex.Store 构造器选项
const store = new Vuex.Store({
  state: {
    accessToken: uni.getStorageSync(AccessTokenKey), // 访问令牌
    refreshToken: uni.getStorageSync(RefreshTokenKey), // 刷新令牌
    userInfo: {},
    userType:'',   //1是会员，2是管理员，3教师，4是学生
    userId:'',
    requestBase:'',
    dictDataList:[]
  },
  getters: {
    accessToken: state => state.accessToken,
    refreshToken: state => state.refreshToken,
    // userInfo: state => state.userInfo,
    userId:state=>state.userId,
    hasLogin: state => !!state.accessToken,
    requestBase:state=>state.requestBase,
    dictDataList:state=>state.dictDataList
  },
  mutations: {
    SET_REQUEST_BASE(state,base){
      state.requestBase = base;
    },
    // 更新 state 的通用方法
    SET_STATE_ATTR(state, param) {
      if (param instanceof Array) {
        for (let item of param) {
          state[item.key] = item.val
        }
      } else {
        state[param.key] = param.val
      }
    },
    // 设置字典
    SET_DICT_DATA(state,data){
      state.dictDataList = data;
    },
    // 更新令牌
    async SET_TOKEN(state, data) {
      // 设置令牌
      const { accessToken, refreshToken,userId,userType } = data;
      state.userType = userType
      state.accessToken = accessToken
      state.refreshToken = refreshToken
      state.userId = userId;
      uni.setStorageSync('userId',userId)
      uni.setStorageSync(AccessTokenKey, accessToken)
      uni.setStorageSync(RefreshTokenKey, refreshToken)
      if(userType ==3){
         var res = await getTeacherUserInfo({id:userId})
      }else if(userType ==4){
        var res = await getUserInfo({id:userId})

      }

      uni.setStorageSync('userInfo',res.data)
      state.userInfo = res.data
       console.log("state",state.userInfo)
      // 加载用户信息
      // this.dispatch('ObtainUserInfo')

    },
    // 更新用户信息
    SET_USER_INFO(state, data) {
      state.userInfo = data
      uni.setStorageSync('userInfo',data)
    },
    // 清空令牌 和 用户信息
    CLEAR_LOGIN_INFO(state) {
      uni.removeStorageSync(AccessTokenKey)
      uni.removeStorageSync(RefreshTokenKey)
      state.accessToken = ''
      state.refreshToken = ''
      state.userInfo = {}
    }
  },
  actions: {
    //账号登录
    Login({ state, commit }, { type, data }) {
      if (type === 0) {

        return passwordLogin(data).then(res => {

          if(!res.data){
            return uni.$u.toast('系统错误');
          }

          commit('SET_TOKEN', res.data)
          let base = '';
          if(res.data.userType==1){

          }else if(res.data.userType==2){
               base = '/admin-api'
          }else if(res.data.userType==3){
               base = '/teacher-api'
          }
          else if(res.data.userType==4){
            base = '/student-api'
          }
          commit('SET_REQUEST_BASE',base)
        })
      } else if (type === 1) {
        return smsLogin(data).then(res => {
          commit('SET_TOKEN', res.data)
        })
      }else if(type ==10){
        // commit('SET_TOKEN', data)
        let base = '';
        if(data.userType==1){

        }else if(data.userType==2){
             base = '/admin-api'
        }else if(data.userType==3){
             base = '/teacher-api'
        }
        else if(data.userType==4){
          base = '/student-api'
        }
        commit('SET_REQUEST_BASE',base)
         commit('SET_TOKEN', data)

      } else {
        return weixinMiniAppLogin(data).then(res => {
          commit('SET_TOKEN', res.data)
        })
      }
    },
    // 退出登录
    async Logout({ state, commit }) {
      commit('CLEAR_LOGIN_INFO')
      // await logout()
      uni.navigateTo({
        url:'/pages/login/account'
      })
    },
    // 获得用户基本信息
    async ObtainUserInfo({ state, commit }) {
      const res = await getUserInfo()
      commit('SET_USER_INFO', res.data)
    }
  }
})

export default store
